package sword.offer;

import java.util.Arrays;

/**
 * 请实现一个函数，把字符串 s 中的每个空格替换成"%20"。
 *
 * @author 胡宇轩
 * @link https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof/
 * @Email: yuxuan.hu01@bianlifeng.com
 */
public class Five {
    public void run(){
        Solution2 solution2 = new Solution2();
        System.out.println(solution2.replaceSpace("We are happy"));
    }

    class Solution {
        public String replaceSpace(String s) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < s.length(); i++) {
                if(s.charAt(i) == ' '){
                    sb.append("%20");
                }else{
                    sb.append(s.charAt(i));
                }
            }
            return sb.toString();
        }
    }

    class Solution2 {
        public String replaceSpace(String s) {
            int spaceNum = 0;
            for(char c : s.toCharArray()){
                if(c == ' '){spaceNum++;}
            }

            int len = spaceNum * 2 + s.length();
            char[] resultArr = new char[len];
            len -= 1;
            for (int i = s.length()-1; i >= 0; i--) {
                if(s.charAt(i)==' '){
                    resultArr[len--] = '0';
                    resultArr[len--] = '2';
                    resultArr[len--] = '%';
                }else{
                    resultArr[len--] = s.charAt(i);
                }
            }
            return new String(resultArr);
        }
    }
}
